<template>
  <div class="project-template-preview-simple">
    <!-- 预览头部 -->
    <div class="preview-header">
      <div class="preview-title">
        <h2>{{ projectConfig.name || '项目模板预览' }}</h2>
        <div class="project-info">
          <span>版本: {{ projectConfig.version || '1.0.0' }}</span>
          <span>状态: {{ getStatusText(projectConfig.status) }}</span>
        </div>
      </div>
      <div class="preview-actions">
        <!-- <el-button type="success" @click="handlePreviewDocument" :loading="loading">
          <el-icon><View /></el-icon> -->
          <!-- 预览文档 -->
        <!-- </el-button> -->
        <el-button type="primary" @click="handleGenerateWord" :loading="loading">
          <el-icon><Document /></el-icon>
          生成Word
        </el-button>
      </div>
    </div>

    <!-- 配置概览 -->
    <div class="config-overview">
      <el-card>
        <template #header>
          <span>配置概览</span>
        </template>
        <div class="overview-stats">
          <div class="stat-item">
            <div class="stat-number">{{ totalSections }}</div>
            <div class="stat-label">章节数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalForms }}</div>
            <div class="stat-label">表单数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalFields }}</div>
            <div class="stat-label">字段数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 使用FormPreview组件显示所有字段 -->
    <div class="form-preview-container">
      <template v-if="structuredData.length">
        <div class="section-divider" v-for="section in structuredData" :key="section.id">
          <h2 class="section-title">{{ section.name }}</h2>
          
          <div v-for="form in section.forms" :key="form.id" class="form-section">
            <h3 class="form-title">
              {{ form.name }}
              <el-tag size="small" type="info">{{ form.id }}</el-tag>
            </h3>
            
            <div v-if="form.fields?.length" class="form-preview-wrapper">
              <FormPreview :fields="form.fields" />
            </div>
            <div v-else class="no-fields">
              <el-empty description="暂未配置字段" :image-size="60" />
            </div>
          </div>
        </div>
      </template>
      <div v-else class="no-data">
        <el-empty description="暂未配置章节和表单">
          <el-button type="primary" @click="handleUpdateProject">
            开始配置
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { View, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useProjectStore } from '@/stores/project'
import FormPreview from '@/components/types/FormPreview.vue'

const props = defineProps({
  projectData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update-project', 'generate-word'])

const router = useRouter()
const projectStore = useProjectStore()

// 响应式数据
const loading = ref(false)
const fullProjectConfig = ref(null)

// 获取完整项目配置
const fetchProjectConfig = async () => {
  if (!props.projectData.id && !props.projectData._id) {
    console.warn('项目ID不存在，使用默认数据')
    return
  }

  loading.value = true
  try {
    const projectId = props.projectData.id || props.projectData._id
    const config = await projectStore.fetchProjectConfig(projectId)
    fullProjectConfig.value = config
  } catch (error) {
    console.error('获取项目配置失败:', error)
    // 使用props中的数据作为fallback
    fullProjectConfig.value = props.projectData
  } finally {
    loading.value = false
  }
}

// 计算属性
const projectConfig = computed(() => {
  return fullProjectConfig.value || props.projectData
})

const configSections = computed(() => {
  console.log('projectConfig:', projectConfig.value)
  console.log('configSections:', projectConfig.value.configSections)
  return projectConfig.value.configSections || []
})

const totalSections = computed(() => configSections.value.length)

const totalForms = computed(() => {
  return configSections.value.reduce((total, section) => {
    return total + (section.forms?.length || 0)
  }, 0)
})

const totalFields = computed(() => {
  return configSections.value.reduce((total, section) => {
    return total + (section.forms?.reduce((formTotal, form) => {
      return formTotal + (form.config?.fields?.length || 0)
    }, 0) || 0)
  }, 0)
})

// 结构化数据，用于分段显示
const structuredData = computed(() => {
  const result = configSections.value.map(section => ({
    id: section.id || section._id,
    name: section.name,
    forms: (section.forms || []).map(form => ({
      id: form.id || form._id,
      name: form.name,
      fields: form.config?.fields || []
    }))
  }))
  console.log('structuredData:', result)
  return result
})

// 所有字段的扁平化数组（如果需要一次性显示所有字段）
const allFields = computed(() => {
  const fields = []
  configSections.value.forEach(section => {
    console.log(section,'section')
    section.forms?.forEach(form => {
      if (form.config?.fields?.length) {
        fields.push(...form.config.fields)
      }
    })
  })
  console.log(fields,'fields')
  return fields
})

// 方法
const getStatusText = (status) => {
  const map = {
    active: '进行中',
    completed: '已完成',
    paused: '已暂停'
  }
  return map[status] || status
}

const handlePreviewDocument = () => {
  router.push('/preview')
}

const handleGenerateWord = () => {
  emit('generate-word', projectConfig.value)
}

const handleUpdateProject = () => {
  emit('update-project', projectConfig.value)
}

// 生命周期
onMounted(() => {
  // 如果有项目ID，获取完整配置
  if (props.projectData.id || props.projectData._id) {
    fetchProjectConfig()
  }
})
</script>

<style lang="scss" scoped>
.project-template-preview-simple {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .preview-title {
      h2 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 20px;
      }

      .project-info {
        display: flex;
        gap: 16px;
        color: #606266;
        font-size: 14px;

        span {
          padding: 4px 8px;
          background: #f5f7fa;
          border-radius: 4px;
        }
      }
    }

    .preview-actions {
      display: flex;
      gap: 12px;
    }
  }

  .config-overview {
    margin-bottom: 24px;

    .overview-stats {
      display: flex;
      gap: 32px;

      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .form-preview-container {
    .section-divider {
      margin-bottom: 40px;
      
      .section-title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 20px;
        padding-bottom: 8px;
        border-bottom: 2px solid #409eff;
      }

      .form-section {
        margin-bottom: 32px;
        padding: 20px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        .form-title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 16px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 16px;
          padding-bottom: 8px;
          border-bottom: 1px solid #ebeef5;
        }

        .form-preview-wrapper {
          padding-top: 8px;
        }

        .no-fields {
          padding: 20px;
          text-align: center;
        }
      }
    }

    .no-data {
      padding: 60px;
      text-align: center;
    }
  }
}
</style>